<script setup>
import {ajax,useDlg} from 'framework'
import {ref,reactive, onMounted, onUnmounted} from 'vue'
import EChart from "../coms/EChart.vue";
import dataease from "./dataease.vue";

const reloading = ref(false)


function reboot() {
  reloading.value = true
  ajax.get('console/restart').then(r => {
    let id = r.data
    let requestContextId = () => {
      let success = false
      ajax.post('console/context_id').then(r => {
        if (r.data != id) {
          reloading.value = false
          location.reload()
        } else {
          setTimeout(requestContextId, 1000)
        }
      }).catch(e => {
        setTimeout(requestContextId, 1000)
      })
    }
    setTimeout(requestContextId, 1000)
  }).catch(e => {
    if (e.code == 100) {
      reloading.value = false
    } else {
      let requestContextId = () => {
        let success = false
        ajax.post('plugins/context_id').then(r => {
          location.reload()
        }).catch(e => {
          setTimeout(requestContextId, 1000)
        })
      }
      setTimeout(requestContextId, 1000)
    }
  })
}

const version = ref('unknown'), startTime = ref(''), diskRatio = ref('')
ajax.get('console/application_info').then(r => {
  version.value = r.data.frameWorkVersion;
  startTime.value = r.data.lastStartTime;
})
const jdkInfo = ref({})
ajax.get("console/jdk_info").then(r => {
  jdkInfo.value = r.data
})


ajax.get("console/disk_info").then(r => {
  let dt = r.data
  diskRatio.value = `${dt.used}/${dt.total} (${dt.ratio}%)`
})
const processInfo = ref({})
const memoryInfo = ref({})
let chart=null

const chartInit=(_chart)=>{
  chart=_chart;
}
/**
 *   "totalMEM": "80.18",
 *         "MEM": "0.96",
 *         "totalCPU": "11.70",
 *         "CUP": "0.04"
 * @type {{cpu: *[]}}
 */
const processDatas = {
  totalMEM: [],
  MEM: [],
  totalCPU: [],
  CPU: []
}
const xAxisData = [];
for (var i = 100; i > 0; i--) {
  xAxisData.push(' ');
}
const totalFlowRateOption = {
  animation: false,
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'line' }
  },
  grid: {
    left: 1/*"50px"*/,
    right: 1/*"15px"*/,
    top:1,
    bottom:1
  },
  xAxis: {
    show:false,
    boundaryGap: false,
    data: xAxisData
  },
  yAxis: {
    boundaryGap: false,
    min:0,max:100,
    type:'value'
  },
  series: [
      {
        symbol: "none",/*去掉小圆点*/
        name: '总内存',
        type: 'line',
        areaStyle: {},
        tooltip:{
          valueFormatter:v => v+'%'
        },
        data: processDatas.totalMEM/*,             smooth:true//显示为平滑的曲线*/
      },
    {
      symbol: "none",/*去掉小圆点*/
      name: '进程内存',
      type: 'line',
      areaStyle: {},
      tooltip:{
        valueFormatter:v => v+'%'
      },
      data: processDatas.MEM/*,             smooth:true//显示为平滑的曲线*/
    },
    {
      symbol: "none",/*去掉小圆点*/
      name: '总CPU',
      type: 'line',
      areaStyle: {},
      tooltip:{
        valueFormatter:v => v+'%'
      },
      data: processDatas.totalCPU/*,             smooth:true//显示为平滑的曲线*/
    },
    {
      symbol: "none",/*去掉小圆点*/
      name: '进程CPU',
      type: 'line',
      areaStyle: {},
      tooltip:{
        valueFormatter:v => v+'%'
      },
      data: processDatas.CPU/*,             smooth:true//显示为平滑的曲线*/
    }
  ]
};
const loadProcess = () => {
  ajax.get("console/process_info").then(r => {
    memoryInfo.value = r.data
    for (let k of ['totalMEM','MEM','totalCPU','CPU']) {
      processDatas[k].push(r.data[k])
    }
    if( processDatas['totalMEM'].length>100) {
      for (let k of ['totalMEM','MEM','totalCPU','CPU']) {
        processDatas[k].shift()
      }
    }
    if (chart)
      chart.setOption(totalFlowRateOption);
  }).catch(e=>{
    for (let k of ['totalMEM','MEM','totalCPU','CPU']) {
      processDatas[k].push(0)
    }
    if( processDatas['totalMEM'].length>100) {
      for (let k of ['totalMEM','MEM','totalCPU','CPU']) {
        processDatas[k].shift()
      }
    }
    if (chart)
      chart.setOption(totalFlowRateOption);
  })
}
const ph = setInterval(loadProcess, 1000)
loadProcess()

onMounted(_ => {

})
onUnmounted(_ => {
  clearInterval(ph)
})

//系统更新
const showUpload=ref(false)
const updateForm=reactive({
  path:null,
  file:null
}),rules={}
const uploadPaths=ref([])
ajax.get("console/update_files").then(r=>uploadPaths.value=r.data)
const form=ref()
function doUpdate(){
  let vr = form.value.valid()
  if (vr.result){
    showUpload.value=false
    ajax.upload("console/update",updateForm).then(r=>{
      reboot()
    })
  }

}
const ntfDlg=useDlg('',(data)=>{
  return ajax.post('system/notification',data,{headers:{'Content-Type':'text/plan'}})
})
</script>
<template>
  <div style="display: flex;height: 100%;flex-direction: column;">
    <div style="box-shadow: 2px 1px 4px 0 rgba(0, 21, 41, 0.08);padding: 5px">
      <Button :loading="reloading" icon="icon-reload" text class="bg-trans" size="s" @click="reboot">重启</Button>
      <Button class="bg-trans" icon="icon-upload" text size="s" @click="showUpload=true">上传更新</Button>
      <Button icon="h-icon-warn"  text class="bg-trans" size="s" @click="ntfDlg.open()">发送在线通知</Button>
    </div>
    <div style="flex:1;height: 100%;overflow: hidden;padding: 10px">
      <div style="height: 100%;overflow-y: auto">
        <Row>
          <Cell width="10" class="cell-item">
            <div class="h-panel">
              <div class="h-panel-bar">
                <span class="h-panel-title">基础信息</span>
                <span class="h-panel-right"></span>
              </div>
              <div class="h-panel-body">
                <table class="system-table" style="width: 100%">
                  <tbody>
                  <tr>
                    <td style="width: 100px">平台版本</td>
                    <td>{{ version }}</td>
                  </tr>
                  <tr>
                    <td style="width: 100px">操作系统</td>
                    <td>{{ jdkInfo.system_name }}</td>
                  </tr>
                  <tr>
                    <td style="width: 100px">系统版本</td>
                    <td>{{ jdkInfo.system_version }}</td>
                  </tr>
                  <tr>
                    <td style="width: 100px">磁盘使用</td>
                    <td>{{ diskRatio }}</td>
                  </tr>
                  <tr>
                    <td style="width: 100px">JDK 版本</td>
                    <td>{{ jdkInfo.version }}</td>
                  </tr>
                  <tr>
                    <td style="width: 100px">JDK 厂商</td>
                    <td>{{ jdkInfo.vendor }}</td>
                  </tr>
                  <tr>
                    <td style="width: 100px">启动时间</td>
                    <td>{{ startTime }}</td>
                  </tr>
                  <tr v-if="jdkInfo.dockerId">
                    <td style="width: 100px">DockerID</td>
                    <td>{{jdkInfo.dockerId}}</td>
                  </tr>
                  <tr v-else>
                    <td style="width: 100px">进程ID</td>
                    <td>{{jdkInfo.pid}}</td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </Cell>
          <Cell width="14" class="cell-item">
            <div class="h-panel">
              <div class="h-panel-bar">
                <span class="h-panel-title">运行信息</span>
                <span class="h-panel-right"></span>
              </div>
              <div class="h-panel-body">
                <table style="width: 100%">
                  <tbody>
                  <tr>
                    <td>系统内存:</td>
                    <td>{{ memoryInfo.totalMemory }}</td>
                    <td>已使用:</td>
                    <td>{{ memoryInfo.totalUseMemory }}</td>
                    <td>应用使用:</td>
                    <td>{{ memoryInfo.processMemory }}</td>
                  </tr>
                  </tbody>
                </table>
                <EChart @init="chartInit" style="height: 243px"/>
<!--                <Chart type="line" :data="processInfo" style="height: 206px"/>-->
              </div>
            </div>
          </Cell>
        </Row>
      </div>
    </div>
    <Modal v-model="showUpload" :closeOnMask="false" hasCloseIcon>
      <template #header>系统更新</template>
      <Form ref="form" :model="updateForm" :rules="rules">
        <FormItem label="更新文件" prop="path" required>
          <Select v-model="updateForm.path" :datas="uploadPaths"/>
        </FormItem>
        <FormItem label="文件" prop="file" required>
          <FileInput accept=".jar" v-model="updateForm.file"/>
        </FormItem>
      </Form>
      <template #footer>
        <Button color="primary" @click="doUpdate">更新</Button>
      </template>
    </Modal>
    <Modal v-model="ntfDlg.isOpen" :closeOnMask="false" hasCloseIcon>
      <template #header>系统在线通知</template>
      <Form>
        <FormItem label="通知">
          <Textarea v-model="ntfDlg.data" style="resize: none;height: 120px;width: 300px"/>
        </FormItem>
      </Form>
      <template #footer>
        <Button color="primary" @click="ntfDlg.submit">发送通知</Button>
      </template>
    </Modal>
  </div>
</template>
<style scoped lang="less">
.bg-trans {
  background-color: transparent;
}

.cell-item {
  padding: 10px;
}

.cell-item > * {
  border-radius: 5px;
  box-shadow: 2px 1px 4px 0 rgba(0, 21, 41, 0.08);
}

.system-table {
  border-collapse: collapse;
  --border: 1px solid rgb(235, 238, 245);
  border: var(--border);

  th, td {
    border: var(--border);
    padding: 5px;
    white-space: nowrap;
  }
}
</style>
